package com.kehutong.payment.util;

import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * 微信签名工具类
 *
 * @author wupengfei
 */
public abstract class WechatSignUtils {

    private static Logger logger = LoggerFactory.getLogger(WechatSignUtils.class);

    public static final String MD5 = "MD5";
    public static final String FIELD_SIGN = "sign";
    public static final String SUCCESS = "SUCCESS";

    /**
     * 生成带有 sign 的 XML 格式字符串
     *
     * @param data Map类型数据
     * @param key  API密钥
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
        return generateSignedXml(data, key, MD5);
    }

    /**
     * 生成带有 sign 的 XML 格式字符串
     *
     * @param data     Map类型数据
     * @param key      API密钥
     * @param signType 签名类型
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data, String key, String signType) throws Exception {
        String sign = generateSignature(data, key, signType);
        data.put(FIELD_SIGN, sign);
        return PayUtil.toXml(data);
    }

    /**
     * 判断签名是否正确
     *
     * @param xmlStr XML格式数据
     * @param key    API密钥
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
        Map<String, String> data = PayUtil.xmlToMap(xmlStr);
        if (!data.containsKey(FIELD_SIGN)) {
            return false;
        }
        String sign = data.get(FIELD_SIGN);
        return generateSignature(data, key).equals(sign);
    }

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。使用MD5签名。
     *
     * @param data Map类型数据
     * @param key  API密钥
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
        return isSignatureValid(data, key, MD5);
    }

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。
     *
     * @param data     Map类型数据
     * @param key      API密钥
     * @param signType 签名方式
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key, String signType) throws Exception {
        if (!data.containsKey(FIELD_SIGN)) {
            return false;
        }
        String sign = data.get(FIELD_SIGN);
        return generateSignature(data, key, signType).equals(sign);
    }

    /**
     * 判断签名是否正确
     *
     * @param returnCode 返回码
     * @param resultCode 结果码
     * @param respMap    微信返回的结果
     * @param mchKey     API密钥
     * @param signType   加密类型
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(String returnCode, String resultCode, Map<String, String> respMap, String mchKey, String signType) throws Exception {
        if (SUCCESS.equals(returnCode) && SUCCESS.equals(resultCode)) {
            if (WechatSignUtils.isSignatureValid(respMap, mchKey, signType)) {
                logger.info("签名校验成功");
                return true;
            }
        }
        logger.info("签名校验失败");
        return false;
    }

    /**
     * 生成签名
     *
     * @param data 待签名数据
     * @param key  API密钥
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        return generateSignature(data, key, MD5);
    }

    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data     待签名数据
     * @param key      API密钥
     * @param signType 签名方式
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key, String signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[0]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String each : keyArray) {
            if (each.equals(FIELD_SIGN)) {
                continue;
            }
            // 参数值为空，则不参与签名
            String value = data.get(each);
            if (value != null && !value.trim().equals("")) {
                sb.append(each).append("=").append(value).append("&");
            }
        }
        sb.append("key=").append(key);
        logger.info("微信签名串md5=" + sb.toString());
        if (MD5.equals(signType)) {
            return org.coraframework.util.secret.MD5.MD5Encode(sb.toString()).toUpperCase();
        }
        return HMACSHA256(sb.toString(), key);
    }

    /**
     * 生成 HMACSHA256
     *
     * @param data 待处理数据
     * @param key  密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256Hmac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        sha256Hmac.init(secretKey);
        byte[] array = sha256Hmac.doFinal(data.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

}
